<?php

// First check that the username does not exist, then create the user if it does not. Return an error
// message if either the user exists or the account could not be created. Authenticate the user otherwise,
// so they will be redirected to the main page.
function gpp_create_account()
{
	$db = get_database_connection();
	
	if(!validEmail($_POST['email']))
	{
		return "Please enter a valid e-mail address.";
	}
	
	if(trim($_POST["password"]) == "")
	{
		return "You must enter an e-mail AND password.";
	}	
	
	$email = mysql_real_escape_string($_POST["email"]);
	$firstname = mysql_real_escape_string($_POST["firstname"]);
	$lastname = mysql_real_escape_string($_POST["lastname"]);
	
	// this hashes the string, so we don't actually store it in plaintext. when we check the password,
	// we will hash what the user puts in in exactly this way.
	$password = mysql_real_escape_string(sha1($_POST["password"]));
	
	// First check that there is not an account with this username already
	$query = sprintf("SELECT id FROM student WHERE email = '%s';", $email);
	$result = mysql_query($query);

	if(gpp_good_result($result)) 
	{
		mysql_free_result($result);
		return "Account already exists.";
	}

	// Formulate Query
	// For more examples, see mysql_real_escape_string()
	$query = "INSERT INTO student (name_first, name_last, email, password) values ";
	$query .= sprintf("('%s', '%s', '%s', '%s');", $firstname, $lastname, $email, $password);
	
	// Perform Query
	$result = mysql_query($query);
	
	// Check result
	// This shows the actual query sent to MySQL, and the error. Useful for debugging.
	gpp_print_sql_error($result, $query);
	
	$_SESSION['email'] = $email;
		
	$query = sprintf("SELECT * FROM student WHERE email = '%s';", $email, $password);
	$result = mysql_query($query);
	
	gpp_print_sql_error($result, $query);

	// If the username and password are valid for the system
	if($result && mysql_num_rows($result) > 0)
	{
		$row = mysql_fetch_assoc($result);
		$_SESSION['id'] = $row['id'];
		$_SESSION['email'] = $email;
		$_SESSION['name_first'] = $row['name_first'];
		$_SESSION['name_last'] = $row['name_last'];
		$_SESSION['pursuing'] = $row['pursuing'];
		$_SESSION['semesters_left'] = $row['semesters_left'];
	}
	
	return "Account successfully created.";
}

function gpp_update_account()
{
	$db = get_database_connection();
	
	// $email = mysql_real_escape_string($_POST["email"]);
	$name_first = mysql_real_escape_string($_POST["name_first"]);
	$name_last = mysql_real_escape_string($_POST["name_last"]);
	
	// CHECK IF INT
	$semesters_left = (int)$_POST["semesters_left"];
	if($semesters_left < 1) 
	{
		return "You must have at least one semester left.";
	}
	if($semesters_left > 12)
	{
		return "You must have fewer than thirteen semesters left.";
	}
	$semesters_left = (string)$semesters_left;
	
	$pursuing = mysql_real_escape_string($_POST["pursuing"]);
	
	
	// this hashes the string, so we don't actually store it in plaintext. when we check the password,
	// we will hash what the user puts in in exactly this way.
	
	if(trim($_POST["password"]) != trim($_POST["password2"]))
	{
		return "You must enter the same password twice.";
	}
	if(trim($_POST["password"]) == "")
	{
		$password = false;
	}
	else
	{
		$password = mysql_real_escape_string(sha1($_POST["password"]));
	}
	
	// Update the user's account info. They cannot change their email. If necessary, an admin will do that
	// for them.
	
	if($password)
	{
		$query = "UPDATE student SET name_first = '%s', name_last = '%s', password = '%s', pursuing = '%s', semesters_left = '%s' WHERE email = '%s';";
		$query = sprintf($query, $name_first, $name_last, $password, $pursuing, $semesters_left, $_SESSION["email"]);
	}
	else
	{
		$query = "UPDATE student SET name_first = '%s', name_last = '%s', pursuing = '%s', semesters_left = '%s' WHERE email = '%s';";
		$query = sprintf($query, $name_first, $name_last, $pursuing, $semesters_left, $_SESSION["email"]);
	}
	
	$result = mysql_query($query);
	
	// Check result
	// This shows the actual query sent to MySQL, and the error. Useful for debugging.
	gpp_print_sql_error($result, $query);
	
	$_SESSION['name_first'] = $name_first;
	$_SESSION['name_last'] = $name_last;
	$_SESSION['pursuing'] = $pursuing;
	$_SESSION['semesters_left'] = $semesters_left;
		
	
	return "Account updated.";
}

function gpp_print_sql_error($result, $query)
{
	if (!$result) 
	{
	    $message  = 'Invalid query: ' . mysql_error() . "\n";
	    $message .= 'Whole query: ' . $query;
	    die($message . "<br/>Please report this incident to chris.cahoon@gmail.com.");
	}

}

function gpp_good_result($result)
{
	return ($result && mysql_num_rows($result) > 0);
}

// Test login credentials against the database. If valid, store a cookie that has the username
// and that says the username is authenticated. We are not going for incredible security yet.
function gpp_login()
{
	$db = get_database_connection();
	// ADD SQL QUERY HERE
	// find if the user exists as in gpp_create_user(), also check that the password is correct
	
	if(trim($_POST["email"]) == "" || trim($_POST["password"]) == "")
	{
		return "You must enter an e-mail AND password.";
	}
	
	$email = mysql_real_escape_string($_POST["email"]);

	// This hashes the string, so we don't actually store it in plaintext. When we check the password,
	// we will hash what the user puts in in exactly this way.
	$password = mysql_real_escape_string(sha1($_POST["password"]));
	
	$query = sprintf("SELECT * FROM student WHERE email = '%s' and password = '%s';", $email, $password);
	$result = mysql_query($query);
	
	gpp_print_sql_error($result, $query);

	// If the username and password are valid for the system
	if($result && mysql_num_rows($result) > 0)
	{
		$row = mysql_fetch_assoc($result);
		$_SESSION['id'] = $row['id'];
		$_SESSION['email'] = $email;
		$_SESSION['name_first'] = $row['name_first'];
		$_SESSION['name_last'] = $row['name_last'];
		$_SESSION['pursuing'] = $row['pursuing'];
		$_SESSION['semesters_left'] = $row['semesters_left'];
	}
	else
		return "This username and password combination does not exist.";
	
	mysql_free_result($result);
	
	return "You have been authenticated with username '$username'";
}

function gpp_logout()
{
	unset($_SESSION['email']);
	session_destroy();	
}

function gpp_is_authenticated()
{
	return isset($_SESSION['email']);
}

?>